<template>
  <div class="search-result-page">
    <!-- 登录提示弹窗 -->
    <div v-if="showLoginModal" class="login-modal-overlay">
      <div class="login-modal">
        <div class="login-modal-header">
          <span class="login-icon">
            <i class="login-icon-inner"></i>
          </span>
        </div>
        <h3 class="login-title">请登录账号</h3>
        <p class="login-desc">登录后可查看用户信息和关注用户</p>
        <div class="login-modal-buttons">
          <div class="button-container">
            <button @click="goToLogin" class="login-btn">确定</button>
            <button @click="closeLoginModal" class="cancel-btn">取消</button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 用户选项弹窗 -->
    <div v-if="showUserOptionsModal" class="user-options-modal-overlay" @click="closeUserOptionsModal">
      <div class="user-options-modal" @click.stop>
        <div class="user-option" @click="goToPersonalHome">
          <span class="option-icon">👤</span>
          <span class="option-text">个人主页</span>
        </div>
        <div class="user-option" @click="logout">
          <span class="option-icon">🚪</span>
          <span class="option-text">退出登录</span>
        </div>
      </div>
    </div>
    
    <div class="top-bar">
      <div class="left-aligned-header-items">
        <div class="header-logo" @click="goToMainHome">
          <img src="../assets/logo.png" alt="Logo" class="logo">
          <span class="logo-text">小白盒</span>
        </div>
        <TopBarSearch />
      </div>
      <div class="user-profile">
        <img :src="currentUser.avatar || 'https://img.icons8.com/material/48/guest-male--v1.png'" 
             class="user-avatar" 
             alt="User Avatar" 
             @click="toggleUserOptionsModal" />
        <span class="username" @click="toggleUserOptionsModal">{{ currentUser.nickname || '游客' }}</span>
        <span class="message-icon" @click="goToMessageHome"></span>
      </div>
    </div>
    <div class="main-sections-wrapper">
      <div class="main-sections">
        <div class="search-main-content">
          <div class="chat-header">
            <div class="tab-bar">
              <div :class="['tab-item', activeTab === 'activity' ? 'active' : '']" @click="activeTab = 'activity'">动态</div>
              <div :class="['tab-item', activeTab === 'nickname' ? 'active' : '']" @click="activeTab = 'nickname'">用户</div>
              <div :class="['tab-item', activeTab === 'topic' ? 'active' : '']" @click="activeTab = 'topic'">话题</div>
            </div>
          </div>
          <div class="result-list">
            <template v-if="activeTab === 'activity'">
              <div v-if="loadingActivities" class="loading-container">
                <div class="loading-spinner"></div>
                <div>加载中...</div>
              </div>
              <div v-else-if="activityResults.length > 0">
                <div v-for="activity in activityResults" :key="activity.id" class="activity-card-container" @click="goToActivityDetail(activity.id)">
                  <div class="custom-activity-card">
                    <div class="activity-header">
                      <img class="avatar" :src="activity.userInfo?.avatar || 'https://img.icons8.com/material/48/guest-male--v1.png'" />
                      <span class="nickname">{{ activity.userInfo?.nickname || '匿名用户' }}</span>
                    </div>
                    <div class="activity-main">
                      <div v-if="activity.topicContent" class="activity-topic">
                        <span class="topic-hash">#</span>
                        <span class="topic-text">{{ activity.topicContent }}</span>
                      </div>
                      <div class="activity-content">{{ activity.content }}</div>
                    </div>
                    <!-- 显示封面图片 -->
                    <div class="activity-cover" v-if="getFirstImage(activity)">
                      <img :src="getFirstImage(activity)" class="cover-img" alt="封面图片" />
                    </div>
                    <div class="activity-images" v-if="activity.mediaUrls && parseImages(activity.mediaUrls).length">
                      <template v-for="(media, idx) in parseImages(activity.mediaUrls).slice(0, 4)" :key="idx">
                        <img
                          v-if="/\.(jpg|jpeg|png|gif|webp)$/i.test(media)"
                          :src="media"
                          class="activity-img"
                          @click.stop="onImgClick(activity, idx)"
                          alt="动态图片"
                        />
                        <video
                          v-else
                          :src="media"
                          class="activity-img"
                          @click.stop="onImgClick(activity, idx)"
                          muted
                          preload="metadata"
                          playsinline
                        ></video>
                      </template>
                    </div>
                    <div class="activity-actions">
                      <button class="action-button comment-action" @click.stop="goToActivityComment(activity.id)">
                        <img width="20" height="20" class="action-icon" src="https://img.icons8.com/windows/32/chat-message.png" alt="chat-message"/>
                        <span class="action-num">{{ activity.commentNum || 0 }}</span>
                      </button>
                      <button class="action-button like-action" @click.stop="likeActivity(activity)">
                        <img width="20" height="20" class="action-icon" src="https://img.icons8.com/material-outlined/24/facebook-like--v1.png" alt="facebook-like--v1"/>
                        <span class="action-num">{{ activity.likesCount || 0 }}</span>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else class="empty-tip">暂无更多内容</div>
            </template>
            <template v-else-if="activeTab === 'nickname'">
              <div v-if="nicknameResults.length > 0">
                <div v-for="item in nicknameResults" :key="item.id" class="result-item user-result-item">
                  <div class="user-info" @click="goToUserProfile(item.id)">
                    <img :src="item.avatar || 'https://img.icons8.com/material/48/guest-male--v1.png'"
                         class="user-avatar-icon"
                         alt="nickname"
                         width="40"
                         height="40"
                    />
                    <span class="result-name">{{ item.nickname || item.name }}</span>
                  </div>
                  <div class="follow-action">
                    <button 
                      v-if="item.followStatus === 'mutual'" 
                      class="follow-btn mutual-follow-btn"
                      @click="toggleFollow(item)"
                    >
                      互相关注
                    </button>
                    <button 
                      v-else-if="item.followStatus === 'following'" 
                      class="follow-btn following-btn"
                      @click="toggleFollow(item)"
                    >
                      已关注
                    </button>
                    <button 
                      v-else 
                      class="follow-btn not-following-btn"
                      @click="toggleFollow(item)"
                    >
                      关注
                    </button>
                  </div>
                </div>
              </div>
              <div v-else class="empty-tip">暂无更多内容</div>
            </template>
            <template v-else-if="activeTab === 'topic'">
              <div v-if="loadingTopics" class="loading-container">
                <div class="loading-spinner"></div>
                <div>加载中...</div>
              </div>
              <div v-else-if="topicResults.length > 0">
                <div v-for="item in topicResults" :key="item.id" class="result-item topic-item" @click="showTopicActivities(item)">
                  <img src="https://img.icons8.com/material/96/hashtag.png"
                       class="result-icon"
                       alt="topic"
                       width="24"
                       height="24"
                  />
                  <div class="topic-info">
                    <span class="result-name"># {{ item.content || item.name }}</span>
                    <span class="topic-count">{{ item.topicNum || 0 }}篇内容</span>
                  </div>
                </div>
              </div>
              <div v-else class="empty-tip">暂无更多内容</div>
            </template>
            <template v-else>
              <div class="empty-tip">暂无更多内容</div>
            </template>
          </div>
        </div>
        <div class="hot-community-sidebar">
          <div class="hot-title">白盒热搜</div>
          <ol class="hot-list">
            <li v-for="(item, idx) in hotSearches" :key="idx" class="hot-item" @click="searchHotTopic(item)">
              <span class="hot-rank" :class="'rank-' + (idx+1)">{{ idx+1 }}</span>
              <span class="hot-name">{{ item }}</span>
            </li>
          </ol>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue';
import axios from 'axios';
import TopBarSearch from '../components/TopBarSearch.vue';
import { useRouter, useRoute } from 'vue-router';
import { currentUser } from '../user';

const showLoginModal = ref(false);
const showUserOptionsModal = ref(false);

const activeTab = ref('activity');
const activityResults = ref([]);
const nicknameResults = ref([]);
const topicResults = ref([]);
const loadingActivities = ref(false);
const loadingTopics = ref(false);
const searchQuery = ref('');
const hotSearches = ref([]);
const router = useRouter();
const topicActivities = ref([]);
const showTopicDetail = ref(false);
const currentTopic = ref(null);

// 获取热搜话题
const fetchHotTopics = async () => {
  try {
    const response = await axios.get('/search/history/hot');
    if (response.data.code === 200 && response.data.data) {
      // 从返回的话题对象中提取内容
      hotSearches.value = response.data.data.map(topic => topic.content);
    }
  } catch (error) {
    console.error('获取热搜话题失败:', error);
  }
};

// 点击热搜词进行搜索
const searchHotTopic = (keyword) => {
  // 使用事件总线发送事件，通知TopBarSearch组件填充搜索框
  window.dispatchEvent(new CustomEvent('fill-search-input', { 
    detail: { keyword }
  }));
  // 更新当前搜索关键词
  searchQuery.value = keyword;
  // 重新执行搜索
  fetchResults();
};
const route = useRoute();
const followLoading = ref(false);

// 初始化时处理路由参数
onMounted(() => {
  // 从URL获取搜索关键词
  if (route.query.q) {
    searchQuery.value = route.query.q;
    // 如果指定了类型，切换到对应标签
    if (route.query.type === 'topic') {
      activeTab.value = 'topic';
    }
    // 执行搜索
    fetchResults();
  }
  
  // 获取热搜话题
  fetchHotTopics();
});

function goToMainHome() {
  router.push('/mainpage').then(() => {
    // 页面跳转后刷新页面
    window.location.reload();
  });
}

// 显示话题相关动态
async function showTopicActivities(topic) {
  currentTopic.value = topic;
  showTopicDetail.value = true;
  loadingActivities.value = true;
  
  try {
    // 使用新的优化接口直接查询话题相关动态
    console.log('查询话题ID:', topic.id);
    const response = await axios.get(`/search/topic-activities/${topic.id}`);
    
    // 检查响应数据格式
    const activityItems = response.data && response.data.data ? response.data.data : [];
    topicActivities.value = [];
    
    if (activityItems.length > 0) {
      await Promise.all(activityItems.map(async item => {
        try {
          // 获取用户信息
          let userInfo = { nickname: '匿名用户', avatar: 'https://img.icons8.com/material/48/guest-male--v1.png' };
          try {
            if (item.userId) {
              const userResponse = await axios.get(`http://localhost:8084/api/user/${item.userId}`);
              if (userResponse.data) {
                userInfo = {
                  nickname: userResponse.data.nickname || '匿名用户',
                  avatar: userResponse.data.avatar || 'https://img.icons8.com/material/48/guest-male--v1.png'
                };
              }
            }
          } catch (userError) {
            console.error(`获取用户信息失败 ID:${item.userId}`, userError);
          }
          
          // 添加到话题活动列表
          topicActivities.value.push({
            ...item,
            content: item.content || item.name || '无内容',
            userInfo: userInfo
          });
        } catch (error) {
          console.error(`处理动态数据失败 ID:${item.id}`, error);
          // 添加基本信息，确保UI不会崩溃
          topicActivities.value.push({
            ...item,
            content: item.content || item.name || '无内容',
            userInfo: { nickname: '匿名用户', avatar: 'https://img.icons8.com/material/48/guest-male--v1.png' }
          });
        }
      }));
    }
    
    // 切换到动态标签页显示结果
    activeTab.value = 'activity';
    // 替换当前活动结果为话题相关活动
    activityResults.value = topicActivities.value;
  } catch (error) {
    console.error('获取话题相关动态失败:', error);
    // 如果新接口失败，尝试使用旧接口作为备选
    try {
      const backupResponse = await axios.get(`http://localhost:8085/activity/by-topic/${topic.id}`);
      // 处理旧接口数据...（保留原有逻辑作为备选）
      console.log('使用备选接口获取话题动态', backupResponse.data ? '成功' : '无数据');
    } catch (backupError) {
      console.error('备选接口也失败:', backupError);
    }
  } finally {
    loadingActivities.value = false;
  }
}

async function fetchResults() {
  if (!searchQuery.value) return;
  loadingActivities.value = true;
  loadingTopics.value = true; // 添加话题加载状态
  try {
    const [activityRes, nicknameResponse, topicRes] = await Promise.all([
      axios.get('/search', {
        params: { type: 'activity', keyword: searchQuery.value }
      }),
      axios.get('/search', {
        params: { type: 'nickname', keyword: searchQuery.value }
      }),
      axios.get('/search', {
        params: { type: 'topic', keyword: searchQuery.value }
      })
    ]);
    
    // 设置用户搜索结果
    nicknameResults.value = nicknameResponse.data.data || [];
    
    // 设置话题搜索结果
    console.log('话题搜索结果:', topicRes.data);
    // 处理话题数据，确保每个话题对象都有content属性
    const topicData = topicRes.data.data || [];
    
    // 处理话题数据，确保每个话题对象都有content属性和topicNum属性
    console.log('原始话题数据:', JSON.stringify(topicData));
    
    // 确保话题数据有效
    if (topicData.length === 0 && route.query.type === 'topic' && route.query.q) {
      // 如果从搜索栏跳转过来但没有话题数据，创建一个临时话题对象
      topicData.push({
        id: route.query.topicId || '0',
        content: route.query.q,
        name: route.query.q,
        topicNum: 0
      });
    }
    
    // 获取每个话题的动态数量
    const topicsWithCounts = await Promise.all(topicData.map(async topic => {
      // 如果话题对象没有content属性，但有name属性，则使用name作为content
      const processedTopic = (!topic.content && topic.name) ? { ...topic, content: topic.name } : { ...topic };
      
      // 尝试从多个可能的字段获取话题动态数量
      if (processedTopic.topicNum !== undefined && processedTopic.topicNum !== null) {
        console.log(`话题 ${processedTopic.id || processedTopic.name} 的动态数量(来自topicNum):`, processedTopic.topicNum);
      } else if (processedTopic.topic_num !== undefined && processedTopic.topic_num !== null) {
        processedTopic.topicNum = processedTopic.topic_num;
        console.log(`话题 ${processedTopic.id || processedTopic.name} 的动态数量(来自topic_num):`, processedTopic.topicNum);
      } else if (processedTopic.id) {
        // 如果没有现成的数量信息，尝试通过API获取
        try {
          const countResponse = await axios.get(`/search/topic-activities/${processedTopic.id}`);
          const activityItems = countResponse.data && countResponse.data.data ? countResponse.data.data : [];
          processedTopic.topicNum = activityItems.length;
          console.log(`话题 ${processedTopic.id} 的动态数量(通过API获取):`, processedTopic.topicNum);
        } catch (error) {
          console.error(`获取话题 ${processedTopic.id} 的动态数量失败:`, error);
          processedTopic.topicNum = 0;
        }
      } else {
        // 如果没有任何方式获取数量，则设置为0
        processedTopic.topicNum = 0;
        console.log(`话题 ${processedTopic.id || processedTopic.name} 没有动态数量信息，设置为0`);
      }
      
      return processedTopic;
    }));
    
    // 确保视图更新
    topicResults.value = [];
    await nextTick();
    topicResults.value = topicsWithCounts;
    console.log('更新后的话题数据:', JSON.stringify(topicResults.value));
    
    // 如果有话题搜索结果，自动获取第一个话题的相关动态
    if (topicResults.value.length > 0 && activeTab.value === 'topic') {
      console.log('自动获取第一个话题的相关动态:', topicResults.value[0]);
      showTopicActivities(topicResults.value[0]);
    }
    
    // 获取动态详情
    const activityItems = activityRes.data.data || [];
    activityResults.value = [];
    loadingTopics.value = false; // 话题加载完成
    if (activityItems.length > 0) {
      await Promise.all(activityItems.map(async item => {
        try {
          const detailResponse = await axios.get(`http://localhost:8085/activity/${item.id}`);
          if (detailResponse.data) {
            // 获取用户信息
            let userInfo = { nickname: '匿名用户', avatar: 'https://img.icons8.com/material/48/guest-male--v1.png' };
            try {
              if (detailResponse.data.userId) {
                const userResponse = await axios.get(`http://localhost:8084/api/user/${detailResponse.data.userId}`);
                if (userResponse.data) {
                  userInfo = {
                    nickname: userResponse.data.nickname || '匿名用户',
                    avatar: userResponse.data.avatar || 'https://img.icons8.com/material/48/guest-male--v1.png'
                  };
                }
              }
            } catch (userError) {
              console.error(`获取用户信息失败 ID:${detailResponse.data.userId}`, userError);
            }
            
            // 合并搜索结果和详情数据
            activityResults.value.push({
              ...item,
              ...detailResponse.data,
              content: detailResponse.data.content || item.name || '无内容',
              userInfo: userInfo
            });
          }
        } catch (error) {
          console.error(`获取动态详情失败 ID:${item.id}`, error);
          // 添加基本信息，确保UI不会崩溃
          activityResults.value.push({
            ...item,
            content: item.name || '无内容',
            userInfo: { nickname: '匿名用户', avatar: 'https://img.icons8.com/material/48/guest-male--v1.png' }
          });
        }
      }));
    }
  } catch (error) {
    console.error('搜索失败:', error);
  } finally {
    loadingActivities.value = false;
  }
  
  // 获取用户搜索结果并添加关注状态
  const users = nicknameResults.value;
  
  if (users.length > 0) {
    try {
      // 获取每个用户的详细信息
      const userDetailsPromises = users.map(user => 
        axios.get(`http://localhost:8084/api/user/${user.id}`)
          .then(res => {
            // 更新用户信息
            user.avatar = res.data.avatar || 'https://img.icons8.com/material/48/guest-male--v1.png';
            user.nickname = res.data.nickname || user.name;
            return user;
          })
          .catch(() => {
            // 获取失败时使用默认头像
            user.avatar = 'https://img.icons8.com/material/48/guest-male--v1.png';
            return user;
          })
      );
      
      await Promise.all(userDetailsPromises);
      
      // 如果当前用户已登录，获取关注状态
      if (currentUser.id) {
        // 获取当前用户的关注列表
        const followingRes = await axios.get(`http://localhost:8084/api/user/${currentUser.id}/following`);
        const followingList = followingRes.data || [];
        
        // 获取关注当前用户的用户列表（粉丝）
        const followersRes = await axios.get(`http://localhost:8084/api/user/${currentUser.id}/followers`);
        const followersList = followersRes.data || [];
        
        // 处理每个用户的关注状态
        users.forEach(user => {
          // 默认未关注
          user.followStatus = 'none';
          
          // 检查是否已关注
          const isFollowing = followingList.some(item => item.id === user.id);
          
          // 检查是否被关注
          const isFollower = followersList.some(item => item.id === user.id);
          
          // 设置关注状态
          if (isFollowing && isFollower) {
            user.followStatus = 'mutual'; // 互相关注
          } else if (isFollowing) {
            user.followStatus = 'following'; // 已关注
          }
        });
      } else {
        // 未登录时设置默认状态
        users.forEach(user => {
          user.followStatus = 'none';
        });
      }
    } catch (error) {
      console.error('获取用户信息失败', error);
      // 出错时使用默认状态
      users.forEach(user => {
        user.followStatus = 'none';
        user.avatar = user.avatar || 'https://img.icons8.com/material/48/guest-male--v1.png';
      });
    }
  }
  
  nicknameResults.value = users;
}

onMounted(async () => {
  searchQuery.value = route.query.q || '';
  await fetchResults();
  
  // 如果是话题类型，自动切换到话题标签
  const type = route.query.type;
  const topicId = route.query.topicId;
  
  if (type === 'topic') {
    activeTab.value = 'topic';
    
    // 如果有话题ID，直接获取话题信息并显示相关动态
    if (topicId) {
      try {
        loadingTopics.value = true;
        // 先获取话题信息
        const topicResponse = await axios.get(`http://localhost:8085/topics/${topicId}`);
        if (topicResponse.data) {
          let topic = topicResponse.data;
          
          // 处理话题数据格式，确保有content属性
          if (typeof topic === 'object') {
            // 确保话题对象有content属性
            if (!topic.content && topic.name) {
              topic.content = topic.name;
            }
            // 如果没有content属性，设置一个默认值
            if (!topic.content) {
              topic.content = "话题" + topic.id;
            }
          } else {
            // 如果返回的不是对象，创建一个话题对象
            console.warn('话题数据格式不正确，创建默认话题对象');
            topic = {
              id: topicId,
              content: "话题" + topicId,
              topicNum: 0
            };
          }
          
          console.log('处理后的话题数据:', topic);
          // 直接调用显示话题相关动态的函数
          showTopicActivities(topic);
        }
      } catch (error) {
        console.error('获取话题信息失败:', error);
        // 创建一个默认话题对象，确保UI不会崩溃
        const defaultTopic = {
          id: topicId,
          content: "话题" + topicId,
          topicNum: 0
        };
        showTopicActivities(defaultTopic);
      } finally {
        loadingTopics.value = false;
      }
    }
  }
  
  // 获取热搜话题
  fetchHotTopics();
  
  // 加载用户信息
  const userInfo = localStorage.getItem('user');
  if (userInfo) {
    try {
      const user = JSON.parse(userInfo);
      if (user && user.id) {
        // 确保用户ID存在且有效
        currentUser.id = user.id;
        currentUser.nickname = user.nickname || '用户';
        currentUser.avatar = user.avatar || 'https://img.icons8.com/material/48/user-male-circle--v1.png';
        
        // 如果用户信息不完整，尝试从服务器获取最新信息
        if (!user.nickname || !user.avatar) {
          try {
            const userRes = await axios.get(`/search/user/${user.id}`);
            if (userRes.data && userRes.data.data) {
              currentUser.nickname = userRes.data.data.nickname || currentUser.nickname;
              currentUser.avatar = userRes.data.data.avatar || currentUser.avatar;
              
              // 更新本地存储的用户信息
              const updatedUser = {...user, nickname: currentUser.nickname, avatar: currentUser.avatar};
              localStorage.setItem('user', JSON.stringify(updatedUser));
            }
          } catch (e) {
            console.error('获取用户详细信息失败:', e);
          }
        }
      } else {
        // 用户ID无效，设置为游客模式
        currentUser.id = 4;
        currentUser.nickname = '游客';
        currentUser.avatar = 'https://img.icons8.com/material/48/guest-male--v1.png';
      }
    } catch (error) {
      console.error('解析用户信息失败', error);
      // 设置默认用户信息，避免顶部栏显示未登录
      currentUser.id = 4;
      currentUser.nickname = '游客';
      currentUser.avatar = 'https://img.icons8.com/material/48/guest-male--v1.png';
    }
  } else {
    // 设置默认用户信息，避免顶部栏显示未登录
    currentUser.id = 4;
    currentUser.nickname = '游客';
    currentUser.avatar = 'https://img.icons8.com/material/48/guest-male--v1.png';
  }
});

// 监听路由参数变化，自动刷新
watch(
  () => route.query.q,
  (newQ) => {
    searchQuery.value = newQ || '';
    fetchResults();
  }
);

function goToPersonalHome() {
  router.push(`/user/${currentUser.id}`).then(() => {
    // 页面跳转后刷新页面
    window.location.reload();
  });
}

function goToMessageHome() {
  router.push('/messagehome').then(() => {
    // 页面跳转后刷新页面
    window.location.reload();
  });
}

// 跳转到用户个人信息界面
function goToUserProfile(userId) {
  // 检查是否登录
  if (!currentUser.id || currentUser.nickname === '默认用户' || currentUser.nickname === '游客') {
    showLoginModal.value = true;
    return;
  }
  // 使用router.push代替直接修改location
  router.push(`/user/${userId}`);
}

// 解析媒体URL列表
function parseImages(mediaUrls) {
  if (!mediaUrls) return [];
  if (typeof mediaUrls === 'string') {
    try {
      return JSON.parse(mediaUrls);
    } catch (e) {
      return [mediaUrls];
    }
  }
  return Array.isArray(mediaUrls) ? mediaUrls : [mediaUrls];
}

// 获取第一张图片作为封面
function getFirstImage(activity) {
  if (!activity.mediaUrls) return null;
  const images = parseImages(activity.mediaUrls);
  if (images.length === 0) return null;
  
  // 查找第一个图片类型的媒体
  for (const media of images) {
    if (/\.(jpg|jpeg|png|gif|webp)$/i.test(media)) {
      return media;
    }
  }
  return null;
}

// 跳转到动态详情页
function goToActivityDetail(activityId) {
  if (!activityId) return;
  router.push(`/activity/${activityId}`);
}

// 跳转到动态评论区
function goToActivityComment(activityId) {
  if (!activityId) return;
  router.push(`/activity/${activityId}?showComments=true`);
}

// 处理图片点击事件
function onImgClick(activity, index) {
  // 这里可以实现图片预览功能
  console.log('查看图片', activity.id, index);
  // 如果有图片预览组件，可以在这里调用
}

// 处理动态点赞
async function likeActivity(activity) {
  // 检查是否登录
  if (!currentUser.id || currentUser.nickname === '默认用户' || currentUser.nickname === '游客') {
    showLoginModal.value = true;
    return;
  }
  
  try {
    const response = await axios.post(`http://localhost:8085/activity/${activity.id}/toggle-like?userId=${currentUser.id}`);
    
    if (response.data.success) {
      // 更新点赞数
      if (response.data.liked) {
        activity.likesCount = (activity.likesCount || 0) + 1;
        activity.liked = true;
      } else {
        activity.likesCount = Math.max(0, (activity.likesCount || 0) - 1);
        activity.liked = false;
      }
    } else {
      alert(response.data.message);
    }
  } catch (e) {
    console.error('点赞操作失败:', e);
    alert('点赞操作失败');
  }
}

// 关注/取消关注用户
async function toggleFollow(user) {
  // 检查是否登录
  if (!currentUser.id || currentUser.nickname === '默认用户' || currentUser.nickname === '游客') {
    showLoginModal.value = true;
    return;
  }
  
  if (followLoading.value) return;
  
  followLoading.value = true;
  try {
    if (user.followStatus === 'none') {
      // 关注用户
      await axios.post(`http://localhost:8084/api/user/follow`, null, {
        params: {
          followerId: currentUser.id,
          followingId: user.id
        }
      });
      user.followStatus = 'following';
    } else {
      // 取消关注
      await axios.post(`http://localhost:8084/api/user/unfollow`, null, {
        params: {
          followerId: currentUser.id,
          followingId: user.id
        }
      });
      user.followStatus = 'none';
    }
  } catch (error) {
    console.error('关注操作失败', error);
    alert('操作失败，请稍后重试');
  } finally {
    followLoading.value = false;
  }
}

// 关闭登录提示弹窗
function closeLoginModal() {
  showLoginModal.value = false;
}

// 跳转到登录页面
function goToLogin() {
  router.push('/login');
  showLoginModal.value = false;
}

// 切换用户选项弹窗
function toggleUserOptionsModal() {
  showUserOptionsModal.value = !showUserOptionsModal.value;
}

// 关闭用户选项弹窗
function closeUserOptionsModal() {
  showUserOptionsModal.value = false;
}

// 退出登录
function logout() {
  // 清空用户信息
  currentUser.id = null;
  currentUser.nickname = '默认用户';
  currentUser.avatar = '';
  
  // 清除本地存储
  localStorage.removeItem('user');
  
  // 跳转到登录页面
  router.push('/login').then(() => {
    // 页面跳转后刷新页面
    window.location.reload();
  });
  closeUserOptionsModal();
}

</script>

<style scoped>
.search-result-page {
  width: 100%;
  height: 100vh;
  background-color: #f0f2f5;
  display: flex;
  flex-direction: column;
}
.top-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  height: 50px;
}
.left-aligned-header-items {
  display: flex;
  align-items: center;
  flex-grow: 1;
  width: 100%;
}
.header-logo {
  display: flex;
  align-items: center;
  height: 100%;
  margin-left: 24px;
  cursor: pointer;
}
.logo {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}
.logo-text {
  font-size: 20px;
  font-weight: bold;
  margin-right: 60px;
  width: 100px;
  color: #333;
}
.search-bar-placeholder {
  flex: 1;
}
.user-profile {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 100px;
}
.user-avatar {
  border-radius: 50%;
  margin-right: 10px;
  width: 30px;
  height: 30px;
}
.username {
  font-weight: bold;
  margin-right: 20px;
  font-size: 15px;
  color: #000;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 120px;
}
.message-icon {
  cursor: pointer;
  width: 30px;
  height: 30px;
  display: inline-block;
  background-image: url('https://img.icons8.com/sf-regular/48/messaging-.png');
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  text-indent: -9999px;
  transition: filter 0.2s;
}
.main-sections-wrapper {
  flex-grow: 1;
  margin-top: 50px;
  padding: 20px;
  overflow-y: auto;
  height: calc(100vh - 50px);
  width: 100%;
}
.main-sections {
  display: flex;
  flex-grow: 1;
  gap: 20px;
  height: 100%;
  width: 100%;
  padding: 0 100px;
}
.search-main-content {
  flex: 1;
  min-width: 0;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  display: flex;
  flex-direction: column;
  height: 100%;
}
/* 复用原有内容区样式 */
.chat-header {
  padding: 0 24px;
  border-bottom: 1px solid #eee;
  background: #fff;
  height: 56px;
  display: flex;
  align-items: center;
}
.tab-bar {
  display: flex;
  gap: 32px;
  height: 100%;
  align-items: center;
}
.tab-item {
  font-size: 16px;
  color: #888;
  cursor: pointer;
  padding: 8px 0;
  border-bottom: 2px solid transparent;
  transition: color 0.2s, border-color 0.2s;
}
.tab-item.active {
  color: #000000;
  border-bottom: 2px solid #000000;
}
.result-list {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
}
.result-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px 0;
  border-bottom: 1px solid #f2f2f2;
}
.result-item:last-child {
  border-bottom: none;
}
.user-result-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 5px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.user-info:hover {
  background-color: #f5f5f5;
}

.user-avatar-icon {
  margin-right: 10px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #eee;
}
.result-icon {
  width: 24px;
  height: 24px;
  opacity: 0.7;
}
.result-name {
  font-size: 16px;
  color: #222;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.topic-item {
  cursor: pointer;
  transition: background-color 0.2s;
}

.topic-item:hover {
  background-color: #f5f5f5;
}

.topic-info {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
}

.topic-count {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}
.activity-card-container {
  margin-bottom: 20px;
  width: 100%;
}

.custom-activity-card {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 2px 12px rgba(44,62,80,0.08);
  margin-bottom: 20px;
  padding: 20px;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
  position: relative;
}

.activity-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.avatar {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  margin-right: 10px;
}

.nickname {
  font-weight: bold;
  color: #23232b;
  margin-right: 10px;
}

.user-id {
  font-size: 12px;
  color: #888;
}

.activity-cover {
  margin: 10px 0;
  width: 100%;
  max-height: 200px;
  overflow: hidden;
  border-radius: 8px;
}

.cover-img {
  width: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.activity-card-container {
  cursor: pointer;
  transition: all 0.2s;
}

.activity-card-container:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.activity-main {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.activity-topic {
  display: inline-block;
  color: #004B96;
  font-weight: bold;
  margin-bottom: 5px;
}

.topic-hash {
  color: #004B96;
}

.activity-content {
  color: #444;
  font-size: 15px;
  text-align: left;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  line-height: 1.5;
}

.activity-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.activity-img {
  width: calc((100% - 30px) / 4);
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
  cursor: pointer;
}

.activity-actions {
  display: flex;
  margin-top: 10px;
  gap: 20px;
}

.action-button {
  display: flex;
  align-items: center;
  margin-right: 20px;
  cursor: pointer;
  background: none;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.action-button:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.action-icon {
  opacity: 0.7;
}

.action-num {
  font-size: 14px;
  color: #666;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30px;
  color: #666;
}

.loading-spinner {
  border: 3px solid #f3f3f3;
  border-top: 3px solid #3498db;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
.follow-action {
  margin-left: auto;
}
.follow-btn {
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  border: none;
  outline: none;
}
.mutual-follow-btn {
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #e0e0e0;
}
.following-btn {
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #e0e0e0;
}
.not-following-btn {
  background-color: #333;
  color: white;
}
.empty-tip {
  text-align: center;
  color: #888;
  padding: 40px 0;
  font-size: 16px;
}
.hot-community-sidebar {
  flex-basis: 260px;
  flex-shrink: 0;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  margin-left: 20px;
  padding: 20px 0 10px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 400px;
  height: fit-content;
}
.hot-title {
  font-size: 18px;
  font-weight: bold;
  color: #222;
  margin-bottom: 18px;
}
.hot-list {
  list-style: none;
  padding: 0;
  margin: 0;
  width: 100%;
}
.hot-item {
  display: flex;
  align-items: center;
  padding: 8px 20px;
  border-bottom: 1px solid #f0f0f0;
  font-size: 15px;
  color: #333;
}
.hot-item:last-child {
  border-bottom: none;
}
.hot-rank {
  width: 22px;
  display: inline-block;
  text-align: center;
  font-weight: bold;
  margin-right: 8px;
}
.rank-1 { color: #ff4d4f; }
.rank-2 { color: #ff7a45; }
.rank-3 { color: #ffa940; }
.search-bar-center {
  display: none;
}

/* 登录提示弹窗样式 */
.login-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.login-modal {
  background-color: white;
  padding: 30px 20px;
  border-radius: 12px;
  width: 360px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  text-align: center;
}

.login-modal-header {
  margin-bottom: 20px;
}

.login-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 70px;
  height: 70px;
  border-radius: 50%;
  background-color: #f0f2f5;
}

.login-icon-inner {
  display: inline-block;
  width: 40px;
  height: 40px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23333"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/></svg>');
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.login-title {
  font-size: 22px;
  margin: 15px 0 10px;
  color: #333;
  font-weight: 600;
}

.login-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 25px;
}

.login-modal-buttons {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.button-container {
  display: flex;
  justify-content: center;
  gap: 20px;
  width: 100%;
}

/* 用户选项弹窗样式 */
.user-options-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
  z-index: 1000;
}

.user-options-modal {
  position: absolute;
  top: 50px;
  right: 100px;
  width: 150px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.user-option {
  padding: 12px 16px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: background-color 0.2s;
}

.user-option:hover {
  background-color: #f5f5f5;
}

.option-icon {
  margin-right: 10px;
  font-size: 18px;
}

.option-text {
  font-size: 14px;
  color: #000000;
}

.login-btn, .cancel-btn {
  width: 120px;
  height: 44px;
  border-radius: 22px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.login-btn {
  background-color: #333;
  color: white;
  border: none;
}

.login-btn:hover {
  background-color: #222;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #e0e0e0;
}

.cancel-btn:hover {
  background-color: #eaeaea;
  transform: translateY(-2px);
}
</style>
